<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="选择群" prop="groupId">
        <el-col :span="15">
          <el-form-item prop="groupId">
            <el-select v-model="queryParams.groupId" placeholder="请选择"
                       style="width: 180px" @change="handleQuery">
              <el-option
                  v-for="dict in userGroups"
                  :key="dict.id"
                  :label="dict.groupName"
                  :value="dict.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="时间">
        <el-col :span="15">
          <el-date-picker
              v-model="queryParams.findTime"
              type="daterange"
              @change="handleQuery"
              range-separator="To"
              start-placeholder="Start date"
              end-placeholder="End date"
          />
        </el-col>
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input
            v-model="queryParams.nickname"
            placeholder="请输入昵称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!--      <el-form-item label="租户编号" prop="tenantId">-->
      <!--        <el-input-->
      <!--            v-model="queryParams.tenantId"-->
      <!--            placeholder="请输入租户编号"-->
      <!--            clearable-->
      <!--            @keyup.enter="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">清空</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['group:guRef:applyJoinGroup']"
        >新增
        </el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--            type="success"-->
<!--            plain-->
<!--            icon="Edit"-->
<!--            :disabled="single"-->
<!--            @click="handleUpdate"-->
<!--            v-hasPermi="['group:apply:edit']"-->
<!--        >修改-->
<!--        </el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['group:guRef:deletesApp']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['group:guRef:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="applyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <!--      <el-table-column label="id" align="center" prop="id"/>-->
      <!--      <el-table-column label="用户id" align="center" prop="userId"/>-->
      <!--      <el-table-column label="群id" align="center" prop="groupId"/>-->
      <el-table-column label="群名" align="center" prop="groupName"/>
      <el-table-column label="用户昵称" align="center" prop="nickname"/>
      <el-table-column label="审核状态" align="center">
        <template #default="scope">
          <dict-tag :options="join_app_status" :value="scope.row.appStatus"/>
        </template>

      </el-table-column>
      <el-table-column label="性别" align="center">
        <template #default="scope">
          <dict-tag :options="sys_user_sex" :value="scope.row.sex"/>
        </template>
      </el-table-column>
      <el-table-column label="申请时间" align="center" prop="createTime" width="120px">
        <template #default="scope">
          {{format(scope.row.createTime, 'yyyy-MM-dd')}}
        </template>
      </el-table-column>
      <el-table-column label="修改时间" align="center" prop="updateTime"/>
      <!--      <el-table-column label="备注" align="center" prop="remark"/>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button v-if=" scope.row.appStatus===0 && permitUpdate(scope.row.groupId)" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['group:guRef:joinAppHandle']">
            修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-if="permitUpdate(scope.row.groupId)"
                     v-hasPermi="['group:guRef:deletesApp']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改入群申请对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body :show-close="false">
      <el-form ref="applyRef" :model="form" :rules="rules" label-width="90px">
        <el-form-item v-if="updateF" label="群名称">
          <el-input v-model="form.groupName" disabled></el-input>
        </el-form-item>
        <el-form-item  label="用户名称" >
        <el-input v-model="form.userName" :disabled="updateF" placeholder="请输入用户在群里名称"></el-input>
        </el-form-item>
        <el-form-item v-if="!updateF" label="群分享码" prop="groupCode">
          <el-input v-model="form.groupCode" placeholder="请输入群分享码"></el-input>
        </el-form-item>
        <el-form-item v-if="form.id" label="审核状态">
          <el-col :span="24">
            <el-form-item>
              <el-radio-group v-model="form.appStatus">
                <el-radio
                    v-for="dict in join_app_status"
                    :key="dict.value"
                    :value="dict.value"
                >{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Apply">
import * as applyApi from "@/api/group/apply.js";

const {proxy} = getCurrentInstance();
const {sys_user_sex, join_app_status} = proxy.useDict("sys_user_sex", "join_app_status");

const applyList = ref([]);
const open = ref(false);
const updateF = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
import * as groupServer from "@/api/group/group.js";
import {AES_Decrypt, AES_Encrypt} from "@/utils/jsencrypt.js";
import {format} from "date-fns";

const route = useRoute();
const groupId = ref(Number(AES_Decrypt(route.query.groupId)) === 0 ? undefined : Number(AES_Decrypt(route.query.groupId)));
const resetFlag = ref(false);
const userGroups = ref([])
const groupPermitMap = reactive(new Map())

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    startTime: null,
    findTime: null,
    endTime: null,
    groupName: null,
    groupCode: null,
    userId: null,
    groupId: null,
    nickname: null,
    userName: null,
    appStatus: null,
    sex: null,
    tenantId: null,
  },
  rules: {
    groupCode: [
      {required: true, message: "群分享码", trigger: "blur"}
    ],
    userName: [
      {required: true, message: "用户群名称", trigger: "blur"}
    ],
  }
});

const {queryParams, form, rules} = toRefs(data);
const start = (() => {
  return new Promise(resolve => {
    groupServer.callFindList(null).then(res => {
          userGroups.value = res.data
          userGroups.value.forEach(item => {
            groupPermitMap.set(item.id, item.adminType)
          })
          if (!groupId.value && !resetFlag.value) {
            userGroups.value.forEach(item => {
              if (item.loginDefault === 1) {
                groupId.value = item.id
                queryParams.value.groupId = item.id
              }
            })
          }
          if (!groupId.value && !resetFlag.value) {
            groupId.value = userGroups.value[0].id
            queryParams.value.groupId = userGroups.value[0].id
          }
        }
    ).then(() => {
      // //console.log("start",currentAdmin.value)
      resolve()
    })
  })
})

/** 查询入群申请列表 */
function getList() {
  loading.value = true;
  start().then(() => {
    if (queryParams.value.findTime) {
      queryParams.value.endTime = queryParams.value.findTime[1]
      queryParams.value.startTime = queryParams.value.findTime[0]
    }
    applyApi.listApply(queryParams.value).then(response => {
      applyList.value = response.data.list;
      total.value = response.data.total;
      loading.value = false;
    });
  })
}

function permitUpdate(groupId) {
  // //console.log("-----------",groupPermitMap.get(row.groupId));
  return groupPermitMap.get(groupId) > 0
}

// 取消按钮
function cancel() {
  open.value = false;
  updateF.value = false;
  reset();
}

// 表单清空
function reset() {
  form.value = {
    startTime: null,
    findTime: null,
    endTime: null,
    id: null,
    userId: null,
    groupId: null,
    groupName: null,
    nickname: null,
    username: null,
    appStatus: 0,
    sex: null
  };
  proxy.resetForm("applyRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 清空按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.startTime = null;
  queryParams.value.findTime = null;
  queryParams.value.endTime = null;
  queryParams.value.groupId = undefined;
  queryParams.value.groupName = undefined;
  groupId.value = null;
  resetFlag.value = true;
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加入群申请";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  form.value.id = row.id;
  form.value.groupName = row.groupName;
  form.value.groupId = row.groupId;
  form.value.userName = row.nickname;
  form.value.appStatus = row.appStatus;
  open.value = true;
  updateF.value = true;
  title.value = "修改入群申请";
  //console.log(form.value);

}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["applyRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        applyApi.updateApply(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          updateF.value = false;
          getList();
        });
      } else {
        applyApi.addApply(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });

}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id ? [row.id] : ids.value;

  proxy.$modal.confirm('是否确认删除入群申请编号为"' + _ids + '"的数据项？').then(function () {
    return applyApi.delApply({delIds: _ids});
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('group/apply/export', {
    ...queryParams.value
  }, `apply_${new Date().getTime()}.xlsx`)
}

getList();
</script>
